package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 用户统计
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate beginDate, LocalDate endDate) {
        List<LocalDate> dateList = getDateList(beginDate,endDate);
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        dateList.forEach(date ->{
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            totalUserList.add(userMapper.countByDate(null, endTime));
            newUserList.add(userMapper.countByDate(beginTime, endTime));
        });
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 管理端订单统计
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate beginDate, LocalDate endDate) {
        List<LocalDate> dateList = getDateList(beginDate,endDate);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            orderCountList.add(orderMapper.countByDateAndStatus(beginTime, endTime, null));
            validOrderCountList.add(orderMapper.countByDateAndStatus(beginTime, endTime, Orders.COMPLETED));
        });
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (int i = 0; i < dateList.size(); i++) {
            totalOrderCount += orderCountList.get(i);
            validOrderCount += validOrderCountList.get(i);
        }
        /*//时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();*/
        Double orderCompletionRate = totalOrderCount == 0 ? 0.0 : validOrderCount.doubleValue() / totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 营业额统计
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate beginDate, LocalDate endDate) {
        List<LocalDate> dateList = getDateList(beginDate,endDate);
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date ->{
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Double turnover = orderMapper.getTurnoverByDate(beginTime, endTime, Orders.COMPLETED);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    /**
     * 订单销量top10
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate beginDate, LocalDate endDate) {
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.selectTop10(beginTime, endTime);
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        goodsSalesDTOS.forEach(goodsSalesDTO -> {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        });
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 获取begin到end之间的日期列表
     * @param beginDate
     * @param endDate
     * @return
     */
    private List<LocalDate> getDateList(LocalDate beginDate, LocalDate endDate){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(beginDate);
        while(!beginDate.equals(endDate)){
            beginDate = beginDate.plusDays(1);
            dateList.add(beginDate);
        }
        return dateList;
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response){
        //查询概览运营数据，提供给Excel模板文件
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //将数据填入excel表格中
        try{
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("sky_server/src/main/resources/template/运营数据报表模板.xlsx"));
            XSSFSheet sheet = excel.getSheet("Sheet1");

            // 获取第2行第2列的单元格并设置值
            XSSFCell cell = sheet.getRow(1).getCell(1);
            cell.setCellValue(begin + "至" + end);
            // 设置单元格居中
            XSSFCellStyle cellStyle = excel.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
            // 设置字体
            XSSFFont font = excel.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 16);//设置字体大小
            cellStyle.setFont(font);
            // 左边框会缺失
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
            cell.setCellStyle(cellStyle);

            // 设置概览数据
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

            // 设置明细数据
            for (int i = 0; i < 30; i++){
                businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));
                sheet.getRow(7+i).getCell(1).setCellValue(begin.toString());
                sheet.getRow(7+i).getCell(2).setCellValue(businessDataVO.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                sheet.getRow(7+i).getCell(5).setCellValue(businessDataVO.getUnitPrice());
                sheet.getRow(7+i).getCell(6).setCellValue(businessDataVO.getNewUsers());
                begin = begin.plusDays(1);
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源
            outputStream.flush();
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
